package org.example.weather.bigscreen.core.config;

import com.google.common.collect.Range;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Properties;

@Slf4j
public class DailyTableAlgorithm implements StandardShardingAlgorithm<Date> {
    private Properties props;

    @Override
    public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Date> shardingValue) {
        Date uploadDate = shardingValue.getValue();
        String day = DateFormatUtils.format(uploadDate, "yyyyMMdd");
        if (CollectionUtils.isNotEmpty(availableTargetNames)) {
            for (final String tableName : availableTargetNames) {
                String shardIndex = tableName.substring(tableName.lastIndexOf("_") + 1);
                if (StringUtils.equals(shardIndex, String.valueOf(day))) {
                    return tableName;
                }
            }
        }
        return null;
    }

    @Override
    public Collection<String> doSharding(final Collection<String> availableTargetNames,
                                         final RangeShardingValue<Date> shardingValue) {
        Collection<String> result = new ArrayList<>();
        try {
            Range<Date> dateRange = shardingValue.getValueRange();
            if (CollectionUtils.isNotEmpty(availableTargetNames)) {
                for (final String tableName : availableTargetNames) {
                    String shardIndex = tableName.substring(tableName.lastIndexOf("_") + 1);
                    if (dateRange.contains(DateUtils.parseDate(shardIndex, "yyyyMMdd"))) {
                        result.add(tableName);
                    }
                }
            }
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("table range sharding error");
        }
        return result;
    }

    @Override
    public Properties getProps() {
        return props;
    }

    public void setProps(final Properties props) {
        this.props = props;
    }

    @Override
    public void init(final Properties properties) {
        System.out.println("QuarterDbAlgorithm init");
    }
}
